/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package history;

import avenue.MyWindowEvent;
import avenue.Session;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.Date;
import javax.persistence.EntityManager;
import javax.swing.JOptionPane;
import javax.swing.JSpinner;
import model.Card;
import model.DBManager;
import model.Payment;
import model.Vehicle;
import model.Station;

/**
 *
 * @author admin
 */
public class ListPaymentHistoryForm extends javax.swing.JFrame
{

    EntityManager em;
    Date startDate;
    Date endDate;
    Card card;
    Vehicle vehicle;
    Station st;

    /**
     * Creates new form ListPaymentHistoryForm
     */
    public ListPaymentHistoryForm()
    {
        em = DBManager.em;
        if (!em.getTransaction().isActive())
          {
            em.getTransaction().begin();
          }

        st = Session.loginUser.getStationId();
        initComponents();

        startDateSpinner.setEditor(new JSpinner.DateEditor(startDateSpinner, "dd/MM/yyyy"));
        endDateSpinner.setEditor(new JSpinner.DateEditor(endDateSpinner, "dd/MM/yyyy"));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents()
    {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        selectPaymentQuery = em.createQuery("select c from Payment c where c.stationId=:stationId").setParameter("stationId", st);
        paymentList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(selectPaymentQuery.getResultList());
        jLabel1 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel2 = new javax.swing.JLabel();
        cardBarCodeTextField = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        regNumTextField = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        startDateSpinner = new javax.swing.JSpinner();
        endDateSpinner = new javax.swing.JSpinner();
        jLabel6 = new javax.swing.JLabel();
        searchButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JSeparator();
        jScrollPane1 = new javax.swing.JScrollPane();
        paymentTable = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N
        jLabel1.setText("Ιστορικό Πληρωμών");

        jLabel2.setText("Αριθμός Κάρτας:");
        jLabel2.setToolTipText("");

        jLabel3.setText("Αριθμός Κυκλοφορίας:");
        jLabel3.setToolTipText("");

        jLabel4.setText("Ημερομηνία:");

        jLabel5.setText("Απο:");

        startDateSpinner.setModel(new javax.swing.SpinnerDateModel());

        endDateSpinner.setModel(new javax.swing.SpinnerDateModel());

        jLabel6.setText("Έως:");

        searchButton.setText("Αναζήτηση");
        searchButton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                searchButtonActionPerformed(evt);
            }
        });

        cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        cancelButton.setText("Άκυρο");
        cancelButton.setToolTipText("");
        cancelButton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                cancelButtonActionPerformed(evt);
            }
        });

        paymentTable.getTableHeader().setReorderingAllowed(false);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, paymentList, paymentTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${cardId.barcode}"));
        columnBinding.setColumnName("Card Id");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${vehicleId.regNumber}"));
        columnBinding.setColumnName("Vehicle Id");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${paymentTimestamp}"));
        columnBinding.setColumnName("Payment Timestamp");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${paymentAmount}"));
        columnBinding.setColumnName("Payment Amount");
        columnBinding.setColumnClass(Double.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(paymentTable);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 650, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 675, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addGap(83, 83, 83)
                            .addComponent(searchButton)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 84, Short.MAX_VALUE)
                            .addComponent(cancelButton))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jLabel5)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel3))
                                .addComponent(jLabel6))
                            .addGap(29, 29, 29)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(endDateSpinner, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)
                                .addComponent(cardBarCodeTextField)
                                .addComponent(regNumTextField)
                                .addComponent(startDateSpinner))))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 618, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(52, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cardBarCodeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(regNumTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(44, 44, 44)
                .addComponent(jLabel4)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(startDateSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(endDateSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(searchButton)
                    .addComponent(cancelButton))
                .addGap(18, 18, 18)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 11, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(81, Short.MAX_VALUE))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

        public Card retrieveCardByBarCode(int barCodeC)
    {
        Card cr = null;
        try
          {
            cr = em.createNamedQuery("Card.findByBarcode",
                    Card.class)
                    .setParameter("barcode", barCodeC).getSingleResult();

          }
        catch (javax.persistence.NoResultException ex)
          {
            System.out.println("den iparxei carta");
            System.out.println(ex);
            return null;
          }
        return cr;
    }

    public Vehicle retrieveVehicleByRegistryNumber(String rn)
    {
        Vehicle v = null;
        try
          {
            v = em.createNamedQuery("Vehicle.findByRegNumber",
                    Vehicle.class)
                    .setParameter("regNumber", rn).getSingleResult();
          }
        catch (javax.persistence.NoResultException ex)
          {
            System.out.println("den iparxeiamaxi");
            System.out.println(ex);
            return null;
          }

        return v;
    }

    
    private void searchButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_searchButtonActionPerformed
    {//GEN-HEADEREND:event_searchButtonActionPerformed
        // TODO add your handling code here:
        try
          {
            String strSQL;
            startDate = (Date) startDateSpinner.getValue();
            endDate = (Date) endDateSpinner.getValue();

            if (cardBarCodeTextField.getText().isEmpty())
              {
                //Δεν επιλεξαμε  καρτα
                if (regNumTextField.getText().isEmpty())
                  {
                    //Δεν επιλεξαμε ουτε καρτα ουτε αρ. κυκλοφ.
                    strSQL = "select p from Payment p where p.stationId=:stationId and "
                            + "p.paymentTimestamp>=?1 and p.paymentTimestamp<=?2 order by p.paymentTimestamp desc";
                    selectPaymentQuery = em.createQuery(strSQL)
                            .setParameter("stationId", st)
                            .setParameter(1, startDate)
                            .setParameter(2, endDate);
                    System.out.println("Δεν επιλεξαμε ουτε καρτα ουτε αρ. κυκλοφ.");
                  }
                else if (!regNumTextField.getText().isEmpty())
                  {
                    //Δεν επιλεξαμε  καρτα αλλα επιλεξαμε  αρ. κυκλοφ.
                    vehicle = retrieveVehicleByRegistryNumber(regNumTextField.getText());
                    strSQL = "select p from Payment p where p.stationId=:stationId and "
                            + "p.paymentTimestamp>=?1 and p.paymentTimestamp<=?2 "
                            + "and p.vehicleId=:vehicleId order by p.paymentTimestamp desc";
                    selectPaymentQuery = em.createQuery(strSQL)
                            .setParameter("stationId", st)
                            .setParameter("vehicleId", vehicle)
                            .setParameter(1, startDate)
                            .setParameter(2, endDate);
                    System.out.println("Δεν επιλεξαμε  καρτα αλλα επιλεξαμε  αρ. κυκλοφ.");

                  }
              }
            else if (!cardBarCodeTextField.getText().isEmpty())
              {//Eπιλεξαμε  καρτα
                card = retrieveCardByBarCode(Integer.parseInt(cardBarCodeTextField.getText()));

                if (regNumTextField.getText().isEmpty())
                  {
                    ////Eπιλεξαμε  καρτα αλλα οχι αρ. κυκλοφ.
                    strSQL = "select p from Payment p where p.stationId=:stationId and "
                            + "p.paymentTimestamp>=?1 and p.paymentTimestamp<=?2 "
                            + "and p.cardId=:cardId order by p.paymentTimestamp desc";
                    selectPaymentQuery = em.createQuery(strSQL)
                            .setParameter("stationId", st)
                            .setParameter("cardId", card)
                            .setParameter(1, startDate)
                            .setParameter(2, endDate);
                    System.out.println("Eπιλεξαμε  καρτα αλλα οχι αρ. κυκλοφ.");
                  }
                else if (!regNumTextField.getText().isEmpty())
                  {
                    vehicle = retrieveVehicleByRegistryNumber(regNumTextField.getText());

                    ////Eπιλεξαμε  καρτα KAI αρ. κυκλοφ.
                    strSQL = "select p from Payment p where p.stationId=:stationId and "
                            + "p.paymentTimestamp>=?1 and p.paymentTimestamp<=?2 "
                            + "and p.cardId=:cardId and p.vehicleId=:vehicleId "
                            + "order by p.paymentTimestamp desc";
                    selectPaymentQuery = em.createQuery(strSQL)
                            .setParameter("stationId", st)
                            .setParameter("cardId", card)
                            .setParameter("vehicleId", vehicle)
                            .setParameter(1, startDate)
                            .setParameter(2, endDate);

                    System.out.println("Eπιλεξαμε  καρτα KAI αρ. κυκλοφ.");
                  }
              }
            paymentList.clear();
            paymentList.addAll(selectPaymentQuery.getResultList());
          }
        catch (Exception e)
          {
             JOptionPane.showMessageDialog(this, "Error",
                        "Διελεύσεις", JOptionPane.ERROR_MESSAGE);
              System.out.println(e);
          }

        
        
    }//GEN-LAST:event_searchButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_cancelButtonActionPerformed
    {//GEN-HEADEREND:event_cancelButtonActionPerformed
        // TODO add your handling code here:
        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED, false);
        for (WindowListener l : this.getWindowListeners())
          {
            l.windowClosed(we);
          }
        this.setVisible(false);
        
    }//GEN-LAST:event_cancelButtonActionPerformed


    /**
     * @param args the command line arguments
     */
    public static void main(String args[])
    {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try
          {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
              {
                if ("Nimbus".equals(info.getName()))
                  {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                  }
              }
          }
        catch (ClassNotFoundException ex)
          {
            java.util.logging.Logger.getLogger(ListPaymentHistoryForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
          }
        catch (InstantiationException ex)
          {
            java.util.logging.Logger.getLogger(ListPaymentHistoryForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
          }
        catch (IllegalAccessException ex)
          {
            java.util.logging.Logger.getLogger(ListPaymentHistoryForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
          }
        catch (javax.swing.UnsupportedLookAndFeelException ex)
          {
            java.util.logging.Logger.getLogger(ListPaymentHistoryForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
          }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                new ListPaymentHistoryForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JTextField cardBarCodeTextField;
    private javax.swing.JSpinner endDateSpinner;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private java.util.List<Payment> paymentList;
    private javax.swing.JTable paymentTable;
    private javax.swing.JTextField regNumTextField;
    private javax.swing.JButton searchButton;
    private javax.persistence.Query selectPaymentQuery;
    private javax.swing.JSpinner startDateSpinner;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
